package pl.polidea.imf.blackberry.ui;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.MainScreen;
import pl.polidea.imf.blackberry.service.IMFService;
import pl.polidea.imf.blackberry.service.statemachine.State;
import pl.polidea.imf.blackberry.service.statemachine.StateOffLine;
import pl.polidea.imf.blackberry.service.statemachine.StateOnline;

public class StatusScreen extends MainScreen {
	LabelField statusLabel;
	LabelField statusText;
	LabelField optionsLabel;
	
	ButtonField reregisterButton;
	ButtonField cleanCacheData;
	ButtonField collectSystemLog;
	
	UiController uiController;
	
	MenuItem closeMenuItem = new MenuItem("Close", 0, 0){
		public void run() {
			uiController.closeStatusScreen();
		};
	};
	
	
	public StatusScreen(State state, final UiController uiController) {
		if(uiController==null){
			throw new IllegalArgumentException("Ui controller must be specified");
		}
		this.uiController = uiController;
		
		statusLabel = new LabelField("Status: ");
		statusText = new  LabelField(state.toString());
		optionsLabel = new LabelField("Options: ");
		
		reregisterButton = new ButtonField("Re-register user");
		
		reregisterButton.setChangeListener(new FieldChangeListener(){

			public void fieldChanged(Field field, int context) {
				IMFService.getInstance().uiRequestReRegistration();
				uiController.closeStatusScreen();
			}
			
		});
		
		cleanCacheData = new ButtonField("Clean cache data");
		cleanCacheData.setChangeListener(new FieldChangeListener() {
			
			public void fieldChanged(Field field, int context) {
				IMFService.getInstance().cleanStorage();
				
			}
		});
		
		collectSystemLog = new ButtonField("Collect sytem-logs");
		collectSystemLog.setChangeListener(new FieldChangeListener(){

			public void fieldChanged(Field field, int context) {
				IMFService.getInstance().uiRequestedCollectSystemLog();
				uiController.closeStatusScreen();
				
			}
			
		});
		
		
		add(statusLabel);
		add(statusText);
		add(optionsLabel);
		if(state.equals(new StateOnline(StateOnline.SUB_STATE_ONLINE_ACTIVE)) || state.equals(new StateOffLine(StateOffLine.SUB_STATE_OFFLINE))){
			add(reregisterButton);
		}
		add(cleanCacheData);
		add(collectSystemLog);
		
	}
	
	public void makeMenu(Menu menu, int instance) {
		menu.deleteAll();
		menu.add(closeMenuItem);
	}
	
	public boolean keyDown(int keycode, int time) {
		if (Keypad.key(keycode) == Keypad.KEY_ESCAPE) {
			uiController.closeStatusScreen();
			return true;
		} else {
			return super.keyDown(keycode, time);
		}
	}
	
}
